package com.tai.line;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.XMLConstants;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class mView {
	NewGame line;
	
    private Bitmap []bitmapdraw;
    private short SCORE=0;
    private short []piece;//đánh dấu những quả banh hiện trên màn hình, banh lớn giá trị dương, banh nhỏ giá trị âm.
    private short []mailbox11;
    private short []mailbox10;
    private short []offset;
    private short []offset2;
    private short []path;
    private short []delBlock;
    private short sumDels,sumPath;
    private int begin,end;
    //private short temp,temp1,RUN;
    //private int xt,yt;
    private boolean mplayer,checkDels;
    
    ImageView[] imgs;
    Bitmap bkg;
    TextView txtscore;
	
    int mRow;
	
	public mView(NewGame line)
	{
		this.line = line;
	}
	
	public void Show()
	{
		line.setContentView(R.layout.main3);
        //line.setContentView(R.id.Layout_view);//set layout main lên actyvity line mà line = new game     
        init();
        //bitmapdraw=tool.bitmapArray(BitmapFactory.decodeResource(line.getResources(), R.drawable.image), line);
        bitmapdraw=tool.bitmapArray(line);//line = new game
        CreateBalls();

	}
	
//-----------------------------------------------------------\
//khởi tạo các giá trị
	
    private void init()
    {
        //mRow = 13;
        mRow = 9;
       
       /* mailbox10=new short[]{//13*13
                16,17,18,19,20,21,22,23,24,25,26,27,28,
                31,32,33,34,35,36,37,38,39,40,41,42,43,
                46,47,48,49,50,51,52,53,54,55,56,57,58,
                61,62,63,64,65,66,67,68,69,70,71,72,73,
                76,77,78,79,80,81,82,83,84,85,86,87,88,
                91,92,93,94,95,96,97,98,99,100,101,102,103,
                106,107,108,109,110,111,112,113,114,115,116,117,118,
                121,122,123,124,125,126,127,128,129,130,131,132,133,
                136,137,138,139,140,141,142,143,144,145,146,147,148,
                151,152,153,154,155,156,157,158,159,160,161,162,163,
                166,167,168,169,170,171,172,173,174,175,176,177,178,
                181,182,183,184,185,186,187,188,189,190,191,192,193,
                196,197,198,199,200,201,202,203,204,205,206,207,208};
        mailbox11=new short[]{//15*15
                -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
                -4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,-4,
                -4,13,14,15,16,17,18,19,20,21,22,23,24,25,-4,
                -4,26,27,28,29,30,31,32,33,34,35,36,37,38,-4,
                -4,39,40,41,42,43,44,45,46,47,48,49,50,51,-4,
                -4,52,53,54,55,56,57,58,59,60,61,62,63,64,-4,
                -4,65,66,67,68,69,70,71,72,73,74,75,76,77,-4,
                -4,78,79,80,81,82,83,84,85,86,87,88,89,90,-4,
                -4,91,92,93,94,95,96,97,98,99,100,101,102,103,-4,
                -4,104,105,106,107,108,109,110,111,112,113,114,115,116,-4,
                -4,117,118,119,120,121,122,123,124,125,126,127,128,129,-4,
                -4,130,131,132,133,134,135,136,137,138,139,140,141,142,-4,
                -4,143,144,145,146,147,148,149,150,151,152,153,154,155,-4,
                -4,156,157,158,159,160,161,162,163,164,165,166,167,168,-4,
                -4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4};
        */
        mailbox10=new short[]{
         		12,13,14,15,16,17,18,19,20,
         		23,24,25,26,27,28,29,30,31,
         		34,35,36,37,38,39,40,41,42,
         		45,46,47,48,49,50,51,52,53,
         		56,57,58,59,60,61,62,63,64,
         		67,68,69,70,71,72,73,74,75,
         		78,79,80,81,82,83,84,85,86,
         		89,90,91,92,93,94,95,96,97,
         		100,101,102,103,104,105,106,107,108};
        mailbox11=new short[]{
        		-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
        		-4, 0, 1, 2, 3, 4, 5, 6, 7, 8,-4,
        		-4, 9,10,11,12,13,14,15,16,17,-4,
        		-4,18,19,20,21,22,23,24,25,26,-4,
        		-4,27,28,29,30,31,32,33,34,35,-4,
        		-4,36,37,38,39,40,41,42,43,44,-4,
        		-4,45,46,47,48,49,50,51,52,53,-4,
        		-4,54,55,56,57,58,59,60,61,62,-4,
        		-4,63,64,65,66,67,68,69,70,71,-4,
        		-4,72,73,74,75,76,77,78,79,80,-4,
        		-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,-4,
        };
    	imgs = new ImageView[mRow*mRow];
    	offset=new short[]{-1,-11,1,11};
        offset2=new short[]{1,12,11,10};
        //offset=new short[]{-1,-15,1,15};
        //offset2=new short[]{1,16,15,14};
        //xt=yt=1;
        
        piece=new short[mRow*mRow];
        path=new short[50];
        delBlock=new short[16];
        sumDels=SCORE=0;
        sumPath=-1;
        random1((short)1);//random bóng lớn
        random((short)-1);//random bóng nhỏ
        
    }
	
	
    private void DrawBackground(LinearLayout lo)
    {
    	// khởi tạo Bitmap với kích thước (30*mRow,30*mRow) với hệ bảng màu ARGB 
    	bkg = Bitmap.createBitmap(30*mRow, 30*mRow, Bitmap.Config.ARGB_8888);
    	bkg = BitmapFactory.decodeResource(line.getResources(), R.drawable.background1);
    	lo.setBackgroundDrawable(new BitmapDrawable(bkg));//thiết lập bitmap vừa tạo là nền của layout
    	
    	txtscore = (TextView)line.findViewById(R.id.Score);
    	txtscore.setTextColor(Color.MAGENTA);
    	txtscore.setText("Score: "+SCORE);

    }
    
    private void CreateBalls()
    {
    	LinearLayout layout_main = (LinearLayout) line.findViewById(R.id.View_game);
    	DrawBackground(layout_main);//vẽ nền game
    	//FrameLayout layout_view = (FrameLayout)line.findViewById(R.id.Layout_view);
    	
    	LinearLayout[] layouts = new LinearLayout[mRow]; 

    	LinearLayout.LayoutParams layout_param = new LinearLayout.LayoutParams(
    			LinearLayout.LayoutParams.FILL_PARENT,
    			LinearLayout.LayoutParams.FILL_PARENT, 1);

    	for (int i=0; i < mRow; i++)
    	{
    		layouts[i] = new LinearLayout(line);
    		layouts[i].setOrientation(LinearLayout.HORIZONTAL);
    		layouts[i].setLayoutParams(layout_param);
    		layout_main.addView(layouts[i]);
    	//	layout_view.addView(layouts[i]);
    	}

    	OnClickListener ocl = new OnClickListener() {

			public void onClick(View v) {
				
				int myId = v.getId();//vị trí ô 
	    		if(piece[myId]>0&&!mplayer){
	    			
	    			Log.i("phuong","myId1:"+myId+", piece:" + piece + ", mplayer: " + mplayer);
	    			begin=myId;
	    			mplayer=true;
	    			shakeimage();
	    		
	    		}else if(piece[myId]<=0&&mplayer&&begin!=0||piece[myId]<=0&&begin==0&&mplayer){
	    			end=myId;
	    			Log.i("phuong","myId2:"+myId+", piece:" + piece + ", mplayer: " + mplayer);
	    			sumPath=fpath((short)begin,(short)end);
	    			if(sumPath!=0){//nếu tổng đường đi !=0 thì dừng lắc sau đó update lại bóng
	    				stopshake();
	    				
		    			update();
		    			
		    			//begin=end=0;
		    			//mplayer=false;
	    			}
	    			
	    		}else if(piece[myId]>0){
	    			Log.i("phuong","myId3:"+myId+", piece:" + piece + ", mplayer: " + mplayer);
	    			stopshake();
	    			begin=myId;
	    			shakeimage();
	    		}
			}
		};
    	
    	
    	for(int j=0;j<mRow*mRow;j++){
    		//int x=j%mRow;
    		int y=j/mRow;

    		imgs[j] = new ImageView(line);
    		imgs[j].setLayoutParams(layout_param);
    		imgs[j].setId(j);
    		imgs[j].setOnClickListener(ocl);    
    		
    		if (piece[j]>0)//bóng lớn
    		{
    			imgs[j].setImageDrawable(new BitmapDrawable(bitmapdraw[piece[j]]));
    		}
    		else if(piece[j]<0)//bóng nhỏ
    		{
    			imgs[j].setImageDrawable(new BitmapDrawable(bitmapdraw[-piece[j]+7]));//hiện bóng cùng màu nhưng nhỏ hơn
    		}
    		else //(piece[j]==0)
    		{
    			//imgs[j].setImageDrawable(new BitmapDrawable(bitmapdraw[1]));	
    		}
    		
    		layouts[y].addView(imgs[j]);
    	}
    }
    
//-----------------------------------------------------    

    private void ChangeImage(int id, Drawable dr)
    {
		ImageView iv = (ImageView)line.findViewById(id);
		iv.setImageDrawable(dr);
    }
    
    private void HandleUpdate(final int id)
    {
    	Log.i("phuong","id= "+id);
    	final Handler handler = new Handler(); 
        Timer t = new Timer(); 
        t.schedule(new TimerTask() { 
                public void run() { 
                        handler.post(new Runnable() { 
                                public void run() { 
                                	
                                	if (id >= 0)
                                	{
                                		
                                		ChangeImage(path[id+1], null);
                                		ChangeImage(path[id], new BitmapDrawable(bitmapdraw[piece[begin]]));
                               			
                                		HandleUpdate(id - 1);
                               		}
                               		else
                               		{
                               			piece[end] = piece[begin];
                               			piece[begin] = 0;
                               			sumPath = 0;
                		    			begin=end=0;
                		    			mplayer=false;
                		    			checkDels=delLine();
                		    			if(checkDels){
                		        			for(int k=0;k<sumDels;k++)
                		        			{
                		        				piece[delBlock[k]]=0;
                		        				ChangeImage(delBlock[k], null);
                		        				
                		        			}
                		        			for(int j=0;j<mRow*mRow;j++)
                    		    			{
                    		    				if(piece[j]<0)
                    		    				{
                    		    					ChangeImage(j, new BitmapDrawable(bitmapdraw[-piece[j]+7]));
                    		    				}
                    		    			}
                		        			sumDels=0;
                		        			//cap nhat score
                		        			txtscore.setText("Score: "+SCORE);	
                		        		}
                		        		
                		        		else{
                		        			
                		    			//Cap nhat banh moi
                		    			for(int j=0;j<mRow*mRow;j++)
                		    			{
                		    				if(piece[j]<0)
                		    				{
                		    					piece[j]=(short)-piece[j];
                		    					ChangeImage(j, new BitmapDrawable(bitmapdraw[piece[j]]));
                		    				}
                		    			}
                		    			boolean check = delLine();
                		    			if(check)
                		    				for(int k=0;k<sumDels;k++)
                		        			{
                		        				piece[delBlock[k]]=0;
                		        				ChangeImage(delBlock[k], null);
                		        				
                		        			}
                		    			
                		    			sumDels=0;
            		        			//cap nhat score
            		        			txtscore.setText("Score: "+SCORE);	
                		    			//Them banh moi
                		    			random((short)-1);
                		    			for(int j=0;j<mRow*mRow;j++)
                		    			{
                		    				if(piece[j]<0)
                		    				{
                		    					ChangeImage(j, new BitmapDrawable(bitmapdraw[-piece[j]+7]));
                		    				}
                		    			}
                		    			
                		    			
                		    			//kiem tra xoa banh
                		    			//checkDels=delLine();
                		        		}
                               		}
                                } 
                        }); 
                } 
        }, 1);     	
    }
    
    //xu ly voi handler
    private void update(){
    	HandleUpdate(sumPath - 1);
/*    	
    	//callHandlerTemp();
*/
    }
    
    private void shakeimage()
    {
    	ImageView iv = (ImageView)line.findViewById(begin);
        Animation shake = AnimationUtils.loadAnimation(line, R.anim.shake);
        shake.setRepeatMode(Animation.RESTART);
        shake.setRepeatCount(Animation.INFINITE);
        iv.startAnimation(shake);

    }
    
    private void stopshake()
    {
    	Log.i("phuong","stopshake");
    	ImageView iv = (ImageView)line.findViewById(begin);
        iv.clearAnimation();

    }
//----------------------------------------------------------------------    
    private void random1(short not){
        Random r=new Random();
        short s1,s2,count=0;
        do{
            //s1=(short)(Math.abs(r.nextInt())%168+1);
        	//s1=(short)(Math.abs(r.nextInt())%(168));//random vị trí từ 0-->168
        	s1=(short)(Math.abs(r.nextInt())%(80));//random vị trí từ 0-->168
            s2=(short)(Math.abs(r.nextInt())%7+1);//random màu bóng từ 1-->7
            if(piece[s1]==0){//
                piece[s1]=(short)(not*s2);//bóng sẽ được đặt tại vị trí s1, vị trí này được lưu trong mảng piece;
                count++;
            }
        }while(count<5);
    }
    private void random(short not){
        Random r=new Random();
        short s1,s2,count=0;
        do{
            //s1=(short)(Math.abs(r.nextInt())%168+1);
        	//s1=(short)(Math.abs(r.nextInt())%(168));//random vị trí từ 0-->168
        	s1=(short)(Math.abs(r.nextInt())%(80));//random vị trí từ 0-->168
            s2=(short)(Math.abs(r.nextInt())%7+1);//random màu bóng từ 1-->7
            if(piece[s1]==0){//
                piece[s1]=(short)(not*s2);//bóng sẽ được đặt tại vị trí s1, vị trí này được lưu trong mảng piece;
                count++;
            }
        }while(count<3);
    }
    
    //xoa khoi la duong thang >=5, duoc luu vao trong mang delBlock
    //va tong so phan tu luu vao bien sumdels
    private boolean delLine(){//xóa bóng ăn điểm
        short p,x,y,count,indx=-1;
        short []del=new short[20];
        for(short i=0;i<20;i++) del[i]=-1;
        for(short i=0;i<77;i++)
        //for(short i=0;i<165;i++)	
            if(piece[i]>0){//nêu là bóng to thì
            	if(i>44) y=1; else y=4;
          //      if(i>116) y=1; else y=4;
                for(short j=0;j<y;j++){
                    count=0; p=mailbox10[i];
                    for(short k=0;k<10;k++){
                        p+=offset2[j]; x=mailbox11[p];
                        if(x==-4||piece[x]!=piece[i]) break;//khác màu thì thoát
        
                        if(piece[x]==piece[i]) count++;//neu cùng màu thì đếm
                    }
                    if(count>=4){
                        short u=0,v,z=mailbox10[i];
                        do{
                            boolean b=false;
                            v=mailbox11[z];
                            for(short t=0;t<20;t++)
                                if(del[t]==-1||b) break; else if(del[t]==v) b=true;
                            if(!b) del[++indx]=v;
                            z+=offset2[j];
                        }while(u++!=count);
                    }
                }
            }
        
        if(indx<4)
        	return false;
        else{
        	for(short i=0;i<(indx+1);i++) delBlock[i]=del[i];
        	sumDels=(short)(indx+1);
        	SCORE +=5+(indx-4)*2;
        	return true;
        }
        
    }
    
    
    //thuat toan tim duong
    //neu tim OK thi luu cac gia tri vao mang path[]
    //va tong so nuoc di duoc luu vao bien sumPath;
    
    private short fpath(short begin,short end){
        boolean []mask=new boolean[mRow*mRow];
        short []gen_dat=new short[mRow*mRow];//tập các đỉnh có thể di chuyển dc nhưng chưa xét
        short []pt=new short[mRow*mRow];
        short []gen_temp=new short[100];
      //  short []gen_temp=new short[50];
        short x,y,indx=1,count;
        gen_dat[indx-1]=begin; mask[begin]=true;//gán phần tử đầu tiên của gan_dat =begin.
        while(indx>0){
            count=0;
            Log.i("phuong","indx= " + indx);
            for(short i=0;i<indx;i++){
                short tmp=gen_dat[i];
                for(short j=0;j<4;j++){
                    x=mailbox10[gen_dat[i]]; x+=offset[j]; y=mailbox11[x];
                    if((y!=-4&&piece[y]<=0&&!mask[y])){//nếu không đụng biên và ko có bi hoặc bi nhỏ và vị trí y chưa đánh dấu
                        gen_temp[count++]=y;//luu các đỉnh có thể di chuyển dc
                        pt[y]=tmp;//lưu các đỉnh đã xét//gán vị trí có nhãn là vị trí đang xet để sau này tìm đường đi ngắn nhất
                        mask[y]=true;
                    }
                    if(mask[end]){//nếu tới đích thì dừng
                        short u=0,v=end;//đánh dấu lại đường đi
                        do{
                            path[u++]=v;
                            v=pt[v];
                        }while(v!=begin);
                        path[u]=begin;
                        System.gc();
                        return u;
                        
                    }
                }
            }
            for(short k=0;k<count;k++) gen_dat[k]=gen_temp[k];//gán lại các đỉnh tạm thỏa == các đỉnh đang xét: sau đó lấy lần lượt các đỉnh trong mảng gen_dat ra xet
            indx=count;
        }
        System.gc();
        return 0;
    }
}